package com.crawler.downloader;

import com.crawler.api.CrawlerDownloader;
import com.crawler.model.CrawlerPageInfo;
import com.crawler.model.CrawlerRequestInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Iterator;
import java.util.Map;

@Service("")
@Slf4j
public class RestTemplateCrawlerDownloader implements CrawlerDownloader {


    @Autowired
    RestTemplate restTemplate;

    @Override
    public CrawlerPageInfo download(CrawlerRequestInfo crawlerRequestInfo) {
        log.info("download request: {}", crawlerRequestInfo);
        CrawlerPageInfo crawlerPageInfo = new CrawlerPageInfo();
        // URL
        String url = crawlerRequestInfo.getUrl();
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        Map<String, String> headerMap = crawlerRequestInfo.getHeaderMap();
        if (null != headerMap && !headerMap.isEmpty()) {
            Iterator<Map.Entry<String, String>> iterator = headerMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> next = iterator.next();
                headers.set(next.getKey(), next.getValue());
            }
        }
        //请求参数
        Map<String, String> params = crawlerRequestInfo.getParamMap();
        HttpEntity httpEntity = new HttpEntity(headers);
        // 请求方法
        String method = crawlerRequestInfo.getMethod();
        ResponseEntity<String> request =null;
        if ("GET".equals(method)) {
            request = restTemplate.getForEntity(url, String.class, httpEntity, params);
        }
        if("POST".equals(method)){
           request = restTemplate.postForEntity(url, httpEntity,String.class);
        }
        crawlerPageInfo.setStatus(request.getStatusCodeValue());
        crawlerPageInfo.setBody(request.getBody());
        HttpHeaders httpHeaders = request.getHeaders();
        return crawlerPageInfo;
    }


}
